import { Article, Channel } from '@/types/data'
import { HomeAction } from '@/types/store'

type ChannelType = {
  channels: Channel[]
  allChannel: Channel[]
  active: number
  channelArticles: {
    [key: number]: {
      timestamp: number
      articles: Article[]
    }
  }
}
const initValue: ChannelType = {
  channels: [],
  allChannel: [],
  active: 0,
  channelArticles: {},
}

export default function saveUserChannel(state = initValue, action: HomeAction) {
  if (action.type === 'home/saveUserChannel') {
    return {
      ...state,
      channels: action.payload,
    }
  }
  if (action.type === 'home/getAllChannel') {
    return {
      ...state,
      allChannel: action.payload,
    }
  }
  if (action.type === 'home/changeActive') {
    return {
      ...state,
      active: action.id,
    }
  }
  if (action.type === 'home/saveChannelArticles') {
    const { channel_id, timestamp, articles } = action.payload
    // 获取旧数组 追加新数组  一开始 可能数组为空所以 ? undefined  || []
    const old = state.channelArticles[channel_id]?.articles ?? []
    return {
      ...state,
      channelArticles: {
        ...state.channelArticles,
        [channel_id]: {
          timestamp: +timestamp,
          articles: [...old, ...articles],
        },
      },
    }
  }
  if (action.type === 'home/saveNewChannelArticles') {
    const { channel_id, timestamp, articles } = action.payload
    // 获取旧数组 追加新数组  一开始 可能数组为空所以 ? undefined  || []
    // const old = state.channelArticles[channel_id]?.articles || []
    //  直接下拉刷新获取最新的10条数据 之后再追加
    return {
      ...state,
      channelArticles: {
        ...state.channelArticles,
        [channel_id]: {
          timestamp: +timestamp,
          articles: [...articles],
        },
      },
    }
  }
  return state
}
